import React, { useEffect, useState } from "react";
import Header from "@/components/Header";
import {
  Input,
  Table,
  Button,
  TableColumnsType,
  Spin,
  UploadProps,
  Form,
  message,
  Modal,
  Card,
  Upload,
  Popconfirm,
} from "antd";
import "./css/person.scss";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import Zu from "./zuList/index";
import { DataType, addData, listDate } from "./interface/interfaces";
import axios from "axios";
import moment from "moment";

const { Search } = Input;

export default function PersonCustom() {
  const [spinning] = useState(false);
  const [list, setList] = useState([]); //列表
  const [open, setOpen] = useState<boolean>(false); //添加框
  const [form] = Form.useForm(); //表单
  const [loading, setLoading] = useState(false);
  const [loading2, setLoading2] = useState(false);
  const [loading3, setLoading3] = useState(false);
  const [loading4, setLoading4] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>(""); //照片1
  const [imageUrl2, setImageUrl2] = useState<string>(""); //照片2
  const [imageUrl3, setImageUrl3] = useState<string>(""); //照片3
  const [imageUrl4, setImageUrl4] = useState<string>(""); //照片4
  const [tit, setTit] = useState(""); //表单
  const [openZu, setZuOpen] = useState(false); //租赁框
  const [zuID, setZuID] = useState(0); //租赁ID
  // 列
  const columns: TableColumnsType<DataType> = [
    {
      title: "姓名",
      width: 100,
      dataIndex: "name",
      key: "id",
    },
    {
      title: "手机号",
      width: 100,
      dataIndex: "tell",
      key: "tell",
    },
    {
      title: "身份证号",
      dataIndex: "sfz",
      key: "sfz",
      width: 150,
    },
    {
      title: "注册时间",
      dataIndex: "createAt",
      key: "createAt",
      width: 150,
    },
    {
      title: "消费次数",
      dataIndex: "count",
      key: "count",
      width: 150,
    },
    {
      title: "操作",
      key: "operation",

      width: 150,
      render: (re) => {
        return (
          <div style={{ textAlign: "center" }}>
            <Button type="link" onClick={() => editForm(re)}>
              修改信息
            </Button>
            <Button type="link" onClick={() => zuOpen(re.id)}>
              租赁记录
            </Button>
            <Popconfirm
              title="拉黑该用户"
              description="是否要拉黑？"
              okText="Yes"
              cancelText="No"
              onConfirm={() => blackList(re.id)}
            >
              {" "}
              <Button type="link">拉黑</Button>
            </Popconfirm>

            <Button type="link">举报</Button>
          </div>
        );
      },
    },
  ];
  // 拉黑
  const blackList = async (id: number) => {
    const { data } = await axios.get(
      "http://127.0.0.1:3100/zsl/blackUser?id=" + id
    );
    if (data.code === 200) {
      message.success(data.msg);
      getList();
    }
    console.log(id);
  };
  // 获取列表
  async function getList() {
    const { data } = await axios.get("http://127.0.0.1:3100/zsl/getCustomList");
    if (data.code === 200) {
      data.data.forEach((item: listDate) => {
        item.createAt = moment(item.createAt).format("YYYY-MM-DD HH:mm:ss");
      });
      setList(data.data);
    }
  }

  useEffect(() => {
    getList();
  }, []);

  // 租赁框
  const zuOpen = (id: number) => {
    setZuID(id);
    setZuOpen(true);
  };
  // 表单添加/修改
  async function onFinish(values: addData) {
    if (values.id) {
      const obj = {
        id: values.id,
        name: values.name,
        sfz: values.sfz,
        tell: values.tell,
        Jinname: values.jinName,
        Jintel: values.jinTel,
        photo_z: imageUrl,
        photo_f: imageUrl2,
        driver_z: imageUrl3,
        driver_f: imageUrl4,
      };
      const { data } = await axios.post(
        "http://127.0.0.1:3100/zsl/addCustom",
        obj
      );
      if (data.code === 200) {
        message.success("修改成功");
        setOpen(false);
        form.resetFields();
        getList();
      }
    } else {
      const obj = {
        name: values.name,
        sfz: values.sfz,
        tell: values.tell,
        Jinname: values.jinName,
        Jintel: values.jinTel,
        photo_z: imageUrl,
        photo_f: imageUrl2,
        driver_z: imageUrl3,
        driver_f: imageUrl4,
      };
      const { data } = await axios.post(
        "http://127.0.0.1:3100/zsl/addCustom",
        obj
      );
      if (data.code === 200) {
        message.success("添加成功");
        setOpen(false);
        form.resetFields();
        getList();
      }
    }
  }
  // 表单修改
  const editForm = (data: addData) => {
    setOpen(true);
    setTit("修改");
    console.log(data, "表单··················");

    setImageUrl(data.photo_z);
    setImageUrl2(data.photo_f);
    setImageUrl3(data.driver_z);
    setImageUrl4(data.driver_f);
    form.setFieldsValue(data);
  };
  // 上传图片
  const handleChange: UploadProps["onChange"] = (info) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      const url = info.fileList[0].response.path;
      setLoading(false);
      setImageUrl(url);
    }
  };
  // 第二
  const handleChange2: UploadProps["onChange"] = (info) => {
    if (info.file.status === "uploading") {
      setLoading2(true);
      return;
    }
    if (info.file.status === "done") {
      const url = info.fileList[0].response.path;
      setLoading2(false);
      setImageUrl2(url);
    }
  };
  // 第三
  const handleChange3: UploadProps["onChange"] = (info) => {
    if (info.file.status === "uploading") {
      setLoading3(true);
      return;
    }
    if (info.file.status === "done") {
      const url = info.fileList[0].response.path;
      setLoading3(false);
      setImageUrl3(url);
    }
  };
  // 第四
  const handleChange4: UploadProps["onChange"] = (info) => {
    if (info.file.status === "uploading") {
      setLoading4(true);
      return;
    }
    if (info.file.status === "done") {
      const url = info.fileList[0].response.path;
      setLoading4(false);
      setImageUrl4(url);
    }
  };

  // 封装照片显示文字方法
  function photo(loding: boolean, str: string) {
    return (
      <button style={{ border: 0, background: "none" }} type="button">
        {loding ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>{str}</div>
      </button>
    );
  }
  const uploadButton = photo(loading, "正面");
  const uploadButton2 = photo(loading2, "反面");
  const uploadButton3 = photo(loading3, "正面");
  const uploadButton4 = photo(loading4, "反面");

  // 关闭添加框
  function closeAddModal() {
    setOpen(false);
    form.resetFields();
    setTit("");
    setImageUrl("");
    setImageUrl2("");
    setImageUrl3("");
    setImageUrl4("");
  }
  // 搜索
  const onSearch = async (value: string) => {
    const { data } = await axios.get(
      "http://127.0.0.1:3100/zsl/getCustomList?name=" + value
    );
    console.log(data, "搜索");
  };

  return (
    <div className="storeBigBox">
      <Spin spinning={spinning}>
        <Header title="个人客户" />
        <div className="searchBox">
          <div>
            <span
              style={{
                marginTop: "5px",
                display: "inline-block",
                marginRight: "5px",
              }}
            >
              客户姓名
            </span>
            <Search
              placeholder="请输入内容"
              onSearch={onSearch}
              style={{
                width: 200,
              }}
            />
          </div>
        </div>
        <div className="storeContent">
          <Button
            type="primary"
            style={{ float: "right", marginBottom: "10px" }}
            onClick={() => setOpen(true)}
          >
            添加客户
          </Button>
          <Table
            pagination={{
              defaultPageSize: 3, //默认煤业显示条数
              defaultCurrent: 1, //默认当前页数第二页
              pageSizeOptions: ["3", "5", "10"], //每页显示多少条
              locale: {
                items_per_page: "条/页",
              },
            }}
            columns={columns}
            dataSource={list}
            scroll={{ y: 350 }}
          />
        </div>

        {/* 添加框 */}
        <Modal
          title={tit ? "编辑客户" : "添加客户"}
          open={open}
          onCancel={() => closeAddModal()}
          footer={
            [] // 设置footer为空，去掉 取消 确定默认按钮
          }
        >
          <Card style={{ width: "100%" }}>
            <p style={{ fontWeight: "bold", marginBottom: "5px" }}>基本信息</p>
            <Form onFinish={onFinish} form={form}>
              <div style={{ display: "flex" }}>
                {tit ? (
                  <Form.Item name="id" label="ID">
                    <Input disabled />
                  </Form.Item>
                ) : (
                  ""
                )}
                <Form.Item
                  name="name"
                  label="姓名"
                  rules={[{ required: true, message: "姓名不能为空" }]}
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  name="sfz"
                  label="身份证号"
                  rules={[{ required: true, message: "身份证号不能为空" }]}
                >
                  <Input />
                </Form.Item>
              </div>
              <Form.Item
                name="tell"
                label="联系方式"
                rules={[{ required: true, message: "联系方式不能为空" }]}
              >
                <Input />
              </Form.Item>
              <div>
                <p style={{ fontWeight: "bold", marginBottom: "5px" }}>
                  紧急联系人
                </p>
                <div style={{ display: "flex" }}>
                  <Form.Item name="jinName" label="姓名">
                    <Input style={{ marginLeft: "-10px" }} />
                  </Form.Item>
                  <Form.Item name="jinTel" label="联系方式">
                    <Input />
                  </Form.Item>
                </div>
              </div>
            </Form>
            <p style={{ fontWeight: "bold", marginBottom: "5px" }}>
              身份证照片：
            </p>
            <div style={{ display: "flex" }}>
              <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="http://127.0.0.1:3100/zsl/upload"
                onChange={handleChange}
              >
                {imageUrl ? (
                  <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
                ) : (
                  uploadButton
                )}
              </Upload>

              <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="http://127.0.0.1:3100/zsl/upload"
                onChange={handleChange2}
              >
                {imageUrl ? (
                  <img src={imageUrl2} alt="avatar" style={{ width: "100%" }} />
                ) : (
                  uploadButton2
                )}
              </Upload>
            </div>
            <p style={{ fontWeight: "bold", marginBottom: "5px" }}>
              驾驶证照片：
            </p>
            <div style={{ display: "flex" }}>
              <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="http://127.0.0.1:3100/zsl/upload"
                onChange={handleChange3}
              >
                {imageUrl ? (
                  <img src={imageUrl3} alt="avatar" style={{ width: "100%" }} />
                ) : (
                  uploadButton3
                )}
              </Upload>

              <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="http://127.0.0.1:3100/zsl/upload"
                onChange={handleChange4}
              >
                {imageUrl ? (
                  <img src={imageUrl4} alt="avatar" style={{ width: "100%" }} />
                ) : (
                  uploadButton4
                )}
              </Upload>
            </div>
            {/* 提交按钮 */}

            <Form onFinish={onFinish} form={form}>
              <Form.Item>
                <div style={{ textAlign: "center" }}>
                  {tit ? (
                    <Button
                      type="primary"
                      style={{ marginRight: "10px" }}
                      htmlType="submit"
                    >
                      修改
                    </Button>
                  ) : (
                    <Button
                      type="primary"
                      style={{ marginRight: "10px" }}
                      htmlType="submit"
                    >
                      添加
                    </Button>
                  )}
                  <Button type="primary" htmlType="reset">
                    重置
                  </Button>
                </div>
              </Form.Item>
            </Form>
          </Card>
        </Modal>
        {/* 租赁框 */}
        <Modal
          title="租赁信息"
          open={openZu}
          onCancel={() => setZuOpen(false)}
          footer={
            [] // 设置footer为空，去掉 取消 确定默认按钮
          }
        >
          <Zu id={zuID} />
        </Modal>
      </Spin>
    </div>
  );
}
